package com.liangtian.mdm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.dm.common.enums.Flag;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtils {

    /**
     * 供bootstrap-table专用
     *
     * @param request
     * @param clazz   模块对象
     * @param cover   是否覆盖相同的键值对
     * @return 将request中的参数转换成Map<String, Object>
     */
    public static <T> Map<String, Object> paramToMap(HttpServletRequest request, Class<T> clazz, boolean cover) {

        Map<String, Object> cond = new HashMap<>();
        Enumeration<String> eu = request.getParameterNames();
        while (eu.hasMoreElements()) {
            String key = eu.nextElement();
            String value = request.getParameter(key);
            if (value == null || "".equals(value)) {
                value = "";
            } else {
                if ("filter".equals(key)) {
                    T obj = JSON.parseObject(value, clazz);
                    BeanUtil.transBean2Map(cond, obj, cover);
                    continue;
                }
                value = value.trim();
            }
            cond.put(key, value);
        }
        return cond;
    }

    public static Map<String, Object> paramToMap(HttpServletRequest request) {

        Map<String, Object> cond = new HashMap<>();
        Map<String, String[]> origin = request.getParameterMap();
        for (String key : origin.keySet()) {
            if ("filter".equals(key)) {
                JSONObject json = JSON.parseObject(origin.get(key)[0]);
                for (String jk : json.keySet()) {
                    cond.put(jk, json.get(jk));
                }
            } else {
                String[] vals = origin.get(key);
                if (vals == null || vals.length == 0) {
                    cond.put(key, "");
                } else if (vals.length == 1) {
                    //cond.put(key, vals[0]);
                    // 转义标识符列
                    cond.put(key, Flag.toValue(vals[0], key));
                } else {
                    cond.put(key, vals);
                }
            }
        }
        return cond;
    }

}
